import type { ThemeVarConfig } from './types'
import { PROJECT_PREFIX } from '../../../../types/constants'

export class ThemeVarMapper {
  private static instance: ThemeVarMapper
  private readonly prefix: string = PROJECT_PREFIX

  static getInstance(): ThemeVarMapper {
    if (!ThemeVarMapper.instance) {
      ThemeVarMapper.instance = new ThemeVarMapper()
    }
    return ThemeVarMapper.instance
  }

  /**
   * 生成CSS变量名：--${this.prefix}-theme-${element}-${subElement}-${modifier}-${state}-${property}
   */
  getVarName(config: ThemeVarConfig): string {
    const parts = [this.prefix, 'theme']
    const { element, subElement, status, modifier, state, property, postModifier } = config

    if (element) {
      parts.push(element)
    }

    if (subElement) {
      parts.push(subElement)
    }

    if (status) {
      parts.push(status)
    }

    if (modifier) {
      parts.push(modifier)
    }

    if (state && state !== 'normal') {
      parts.push(state)
    }

    if (property) {
      parts.push(property)
    }

    if (postModifier) {
      parts.push(postModifier)
    }

    return `--${parts.join('-')}`
  }

  /**
   * 获取变量值（带备用值）
   */
  getVarValue(config: ThemeVarConfig, fallback: string = ''): string {
    return `var(${this.getVarName(config)}, ${fallback})`
  }
}
